package com.xhu.water_supply.web.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhu.water_supply.constants.Constants;
import com.xhu.water_supply.dto.Result;
import com.xhu.water_supply.dto.ResultEnum;
import com.xhu.water_supply.dto.ResultUtils;
import com.xhu.water_supply.web.utils.JwtComponent;
import com.xhu.water_supply.web.utils.PayloadDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description 登录认证处理器
 */
@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {
    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;
    @Autowired
    private JwtComponent jwtComponent;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 白名单验证
        String url = request.getRequestURL().toString();
        for(String curr : ignoreUrlsConfig.getIgnoreList()){
            if(url.contains(curr)) return true;
        }
        //2. 非白名单时，需要验证传入的Authorization
        String authorization = request.getHeader("Authorization");
        System.out.println(authorization);
        if(Objects.isNull(authorization)){
            this.responseMessage(response, ResultUtils.returnFail("没有进行授权登录！"));
            return false;
        }
        //3. 验证token
        try{
            PayloadDTO payloadDTO = jwtComponent.verifyTokenByHmac(authorization, Constants.JWT_SECRET);
            //将负载信息对象保存在请求对象中
            request.setAttribute("payload", payloadDTO);
        }catch (Exception ex){
            this.responseMessage(response, ResultUtils.returnFail("授权信息已失效"));
            return false;
        }
        return true;
    }

    /**
     * 响应消息
     * @param response  响应对象
     * @param result   响应的信息对象
     */
    private void responseMessage(HttpServletResponse response, Result result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        ObjectMapper objectMapper = new ObjectMapper();
        //忽略值为默认值的属性
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
        String jsonResult = objectMapper.writeValueAsString(result);

        response.getWriter().write(jsonResult);;
    }
}